#!/usr/bin/env python
import gammu
import re

""" 
class representing message to send and recive
"""
class Sms(dict):
    def __init__(self, text):
	dict.__init__(self)
	self['SMSC'] = dict(Location=1)
	self.setText(text)
    def __init__(self, number, text):
	dict.__init__(self)
	self['SMSC'] = dict(Location=1)
	self.setNumber(number)
	self.setText(text)
    def setText(self, text):
	self['Text'] = text
    def setNumber(self, number):
	self['Number'] = number
    def getText(self):
	return str(self['Text'])
    def getNumber(self):
	number = str(self['Number'])
	if (number[0]=='+'):
	    number = number[3:]
	return number
    def _syntaxFriendly(self):
	p = re.compile("[qQ]?[0-9]+[^a-zA-Z0-9]{1}[a-zA-Z0-9]+")
	m = p.match(self.getText())
	if m:
	    return True
	else:
	    return False
    def getSurveyId(self):
	if not self._syntaxFriendly():
	    raise Exception("Error: SMS is not syntax friendly")
	msg = self.getText()
	p = re.compile("[0-9]+")
	m = p.search(msg)
	if m: 
	    return msg[m.start():m.end()]
	else:
	    raise Exception("Error: SMS is not syntax friendly")
    def getAnswer(self):
	if not self._syntaxFriendly():
	    raise Exception("Error: SMS is not syntax friendly")
	msg = self.getText()
	p = re.compile("[^a-zA-Z0-9]")
	m = p.search(msg)
	if m: 
	    return msg[m.start()+1:]
	else:
	    raise Exception("Error: SMS is not syntax friendly")
    def __str__(self):
	return "SMS from: "+self.getNumber()+"\n"+\
	       "text: "+self.getText()+"\n--"


"""
main method used only for testing
"""
def main():
    sm = gammu.StateMachine()
    sm.ReadConfig()
    sm.Init()
    try: 
	msg = Sms("26661670", "q007:strawberry")
	print msg.getSurveyId(), "answer [", msg.getAnswer(),"]"
	msg = Sms("26661670", "q11 3 ")
	print msg.getSurveyId(), "answer [", msg.getAnswer(),"]"
	msg = Sms("26661670", "Q23.1")
	print msg.getSurveyId(), "answer [", msg.getAnswer(),"]"
	msg = Sms("26661670", "Q5/yes")
	print msg.getSurveyId(), "answer [", msg.getAnswer(),"]"
	msg = Sms("26661670", "117 6")
	print msg.getSurveyId(), "answer [", msg.getAnswer(),"]"
	msg = Sms("26661670", "a11/asfee6")
	print msg.getSurveyId(), "answer [", msg.getAnswer(),"]"
    except Exception, e:
	print e
    #print "sending..."
    #sm.SendSMS(msg)
    #print "...successfully sent"

if __name__=="__main__":
    print __name__
    main()

